package com.huika.dealontop.control.myinfo.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.Response;
import com.google.gson.reflect.TypeToken;
import com.huika.dealontop.GlobalApp;
import com.huika.dealontop.R;
import com.huika.dealontop.config.Constants;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.extend.ActionBarHelper;
import com.huika.dealontop.control.base.extend.BaseActionBarActivity;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.utils.DialogUtils;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.views.IOSAlertDialog;
import com.huika.dealontop.views.ToastMsg;
import com.huika.dealontop.views.cleardit.ClearableEditText;
import com.huika.huikalib.utils.StringUtils;

/**
 * Author: Victor Wu
 * Email: victor-wu*foxmail.com
 * Time: 2015/11/17 15:37
 * Description: &#x4fee;&#x6539;&#x90ae;&#x7bb1;
 */
public class ModifiedEmailActivity extends BaseActionBarActivity implements TextWatcher {

    public static final String USER_ID = "userID";

    private String mUserId;

    private ClearableEditText mEtEmail;
    private ClearableEditText mEtValidate;
    private TextView mTvGetValidate;
    private Button mBtnConfirm;

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_modified_email);
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            mUserId = intent.getStringExtra(USER_ID);
        }
        setResult(RESULT_CANCELED);
    }

    @Override
    protected void initWidget() {
        ActionBarHelper barHelper = getActionBarHelper();
        barHelper.setTitleMsg(UIUtils.getString(R.string.modified_email_title));

        mEtEmail = (ClearableEditText) findViewById(R.id.cet_modified_email_new);
        mEtValidate = (ClearableEditText) findViewById(R.id.cet_modified_email_validate);
        mTvGetValidate = (TextView) findViewById(R.id.tv_modified_email_getValidate);
        mBtnConfirm = (Button) findViewById(R.id.btn_modified_email_confirm);
        mTvGetValidate.setOnClickListener(this);
        mBtnConfirm.setOnClickListener(this);

        //初始化验证码输入框不可输入 ，成功获取验证码后才能输入
        mEtValidate.setFocusable(false);
        mEtValidate.setFocusableInTouchMode(false);

        mEtEmail.addTextChangedListener(this);
        mEtValidate.addTextChangedListener(this);

    }

    @Override
    protected void initLoadingDialog(boolean isTrans) {
        super.initLoadingDialog(isTrans);
        loadingDialog.setCancelable(false);
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.tv_modified_email_getValidate:
                getValidate();
                break;
            case R.id.btn_modified_email_confirm:
                confirm();
                break;
        }
        super.widgetClick(v);
    }

    private String confirmEmail;
    private void confirm() {
        String email = mEtEmail.getText().toString().trim();
        String validate = mEtValidate.getText().toString().trim();

        if (!checkEmail(email))
            return;

        if (!checkValidate(validate))
            return;
        confirmEmail = email;
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("userID", mUserId);
        ajaxParams.putCommonTypeParam("email", email);
        ajaxParams.putCommonTypeParam("validate", validate);
        FormResultRequest<Void> request = new FormResultRequest<>(UrlConstants.UPDATE_EMAIL,
                new Response.Listener<RequestResult<Void>>() {
                    @Override
                    public void onResponse(RequestResult<Void> voidRequestResult) {
                        dismissLoadingDialog();
                        if (voidRequestResult != null) {
                            if (voidRequestResult.flag == 1) {
                                //新密码设置成功!
                                showSuccessDialog();
                                updateUserModel();
                            } else {
                                if (!StringUtils.isEmpty(voidRequestResult.msg)) {
                                    ToastMsg.showToastMsg(UIUtils.getContext(), voidRequestResult.msg);
                                } else {
                                    ToastMsg.showToastMsg(UIUtils.getContext(), UIUtils.getString(R.string.submitted_failure));
                                }
                            }
                        } else {
                            ToastMsg.showToastMsg(UIUtils.getContext(), voidRequestResult.msg);
                        }
                    }
                }, this, new TypeToken<RequestResult<Void>>() {
        }.getType());
        request.setRequestParams(ajaxParams);
        showLoadingDialog(UIUtils.getString(R.string.is_submitted));
        executeRequest(request);
    }

    private void updateUserModel() {
        if(TextUtils.isEmpty(confirmEmail)) return;
        GlobalApp.getUserModel().setEmail(confirmEmail);
    }

    private void showSuccessDialog() {
        setResult(RESULT_OK);
        //提交成功!
        final IOSAlertDialog dialog = DialogUtils.getInstance().createTitleDialog(this, UIUtils.getString(R.string.submitted_successfully));
        dialog.setConfirmText(UIUtils.getString(R.string.register_confirm));
        dialog.setConfirmClickListener(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialog.dismiss();
                finish();
            }
        });
        dialog.show();
    }

    private CountDownTimer cdt;
    //显示验证码倒计时
    private void startCountDownValidate() {

        mEtValidate.setFocusable(true);
        mEtValidate.setFocusableInTouchMode(true);

        mTvGetValidate.setTextColor(UIUtils.getColor(R.color.color_333333));
        mTvGetValidate.setEnabled(false);
        cdt = new CountDownTimer(120000,1000){
            @Override
            public void onTick(long l) {
                mTvGetValidate.setText(String.valueOf(l / 1000) + "s");
            }
            @Override
            public void onFinish() {
                cdt.cancel();
                mTvGetValidate.setEnabled(true);
                mTvGetValidate.setTextColor(UIUtils.getColor(R.color.color_fd702b));
                mTvGetValidate.setText(UIUtils.getString(R.string.register_get_vertification));
            }
        };
        cdt.start();
    }

    public void getValidate() {
        String email = mEtEmail.getText().toString().trim();
        if (!checkEmail(email))
            return;

        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("account", email);
        ajaxParams.putCommonTypeParam("accType", Constants.AccountType.EMAIL);
        ajaxParams.putCommonTypeParam("type", Constants.ValidateType.MODIFIED_EMAIL);
        ajaxParams.putCommonTypeParam("registerSource", Constants.RegisterSource.ANDROID);
        FormResultRequest<Void> request = new FormResultRequest<>(UrlConstants.GETSMSVERIFICATION,
                new Response.Listener<RequestResult<Void>>() {
                    @Override
                    public void onResponse(RequestResult<Void> voidRequestResult) {
                        dismissLoadingDialog();
                        if (voidRequestResult != null && !StringUtils.isEmpty(voidRequestResult.msg)) {
                            ToastMsg.showToastMsg(UIUtils.getContext(), voidRequestResult.msg);

                            startCountDownValidate();
                        }
                    }
                }, this, new TypeToken<RequestResult<Void>>() {
        }.getType());
        request.setRequestParams(ajaxParams);
        showLoadingDialog(UIUtils.getString(R.string.waiting_verification_code));
        executeRequest(request);
    }

    private boolean checkValidate(String validate) {
        if (StringUtils.isEmpty(validate)) {
            ToastMsg.showToastMsg(UIUtils.getContext(), UIUtils.getString(R.string.my_address_mobile_code_des));
            return false;
        }
        if (validate.length() != 6) {
            ToastMsg.showToastMsg(UIUtils.getContext(), UIUtils.getString(R.string.filled_verification_code));
            return false;
        }
        return true;
    }

    private boolean checkEmail(String email) {
        if (StringUtils.isEmpty(email)) {
            ToastMsg.showToastMsg(UIUtils.getContext(), UIUtils.getString(R.string.register_code_empty_email));
            return false;
        }
        if (!StringUtils.isEmail(email)) {
            ToastMsg.showToastMsg(UIUtils.getContext(), UIUtils.getString(R.string.filled_email));
            return false;
        }
        return true;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (!StringUtils.isEmpty(mEtEmail.getText().toString().trim()) && !StringUtils.isEmpty(mEtValidate.getText().toString().trim())) {
            mBtnConfirm.setEnabled(true);
        } else {
            mBtnConfirm.setEnabled(false);
        }
    }

}
